package com.aaa.sb.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * className:LogUtil
 * discription:通知类（切面的实现类）
 * author:luRuiHua
 * createTime:2018-11-23 18:02
 */
//不属于三层架构
@Component//交给spring管理
@Aspect
public class LogUtil {

    //切入点配置//切入点表达式
    @Pointcut(value = "execution(* com.aaa.sb.service.*.*(..))")
    public void pointCutOne() {};
    /**
     * 前置通知
     */
    @Before(value = "pointCutOne()")//切入点指向切入点表达式
    public void beforeSaveLog(JoinPoint joinPoint) {
        //获取目标对象
        String name = joinPoint.getTarget().getClass().getName();
        System.out.println("再调用"+name+"的"+"调用：" + joinPoint.getSignature().getName() + "方法之前，打印。。。");

    }
    /**
     * 后置通知
     */
    @AfterReturning(value = "pointCutOne()")//切入点指向切入点表达式
    public void afterReturningSavelog(JoinPoint joinPoint) {
        //获取目标对象
        String name = joinPoint.getTarget().getClass().getName();
        System.out.println("再调用"+name+"的"+"调用：" + joinPoint.getSignature().getName() + "方法之前，打印。。。");
    }
    /**
     * 异常通知
     * 异常通知注解多了一个throwing = "exception"属性，值和参数列表中的值必须一样
     * 模拟时需要在service制造异常
     */
    @AfterThrowing(value = "pointCutOne()",throwing = "exception")//切入点指向切入点表达式
    public void afterThrowingSavelog(JoinPoint joinPoint,Exception exception) {
        //获取目标对象
        String name = joinPoint.getTarget().getClass().getName();
        System.out.println("再调用"+name+"的"+"调用：" + joinPoint.getSignature().getName() + "方法之前，打印。。。方法时出现了"+exception.getClass().getName()+"异常，异常描述为："+exception.getMessage());
    }
    /**
     * 最终通知
     */
    @After(value = "pointCutOne()")//切入点指向切入点表达式
    public void afterSavelog(JoinPoint joinPoint) {
        //获取目标对象
        String name = joinPoint.getTarget().getClass().getName();
        System.out.println("再调用"+name+"的"+"调用：" + joinPoint.getSignature().getName() + "方法之后，无论有没有异常都会打印。。。");
    }

    /**
     * 环绕通知
     * 参数和其他通知不同
     */
    @Around(value = "pointCutOne()")//切入点指向切入点表达式
    public Object aroundSavelog(ProceedingJoinPoint proceedingJoinPoint) {
        Object proceed = null;
        System.out.println(System.currentTimeMillis()+"执行业务之前。。。。。。。。");
        try {
            proceed = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println(System.currentTimeMillis()+"执行业务方法之后。。。。。。。");
        return proceed;
    }

}
